package com.qf.smsplatform.webmaster.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.webmaster.constans.ResultCode;
import com.qf.smsplatform.webmaster.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Component
public class LoginInterceptor implements HandlerInterceptor {
    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    //前置通知
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登陆
        //我们发现因为这里直接拦截了,没有返回任何数据, 所以前端页面最终是空白的,不合理

        boolean islogin = request.getSession().getAttribute("user") != null;


        if (!islogin) {
            ///没有登录,返回未登录提示
            R error = R.setError(ResultCode.NOT_LOGIN, "请登录", null);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(error));
        }

        return islogin;
    }

    //后置通知
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //视图都处理完之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
